package com.xnx3.wangmarket.admin.controller;

import com.xnx3.j2ee.entity.User;
import com.xnx3.j2ee.func.AttachmentFile;
import com.xnx3.j2ee.service.SqlService;
import com.xnx3.j2ee.service.UserService;
import com.xnx3.j2ee.shiro.ActiveUser;
import com.xnx3.j2ee.vo.UploadFileVO;
import com.xnx3.wangmarket.Utils.ColorUtils;
import com.xnx3.wangmarket.Utils.DownloadPicture;
import com.xnx3.wangmarket.Utils.HttpRequestUtil;
import com.xnx3.wangmarket.Utils.QrcodeUtils;
import com.xnx3.wangmarket.admin.entity.QrCode;
import com.xnx3.wangmarket.admin.service.QrCodeService;
import com.xnx3.wangmarket.admin.util.AliyunLog;
import jdk.nashorn.internal.ir.annotations.Reference;
import org.apache.tomcat.jni.Directory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.io.File;
import java.net.InetAddress;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import static com.xnx3.j2ee.shiro.ShiroFunc.getUser;
import static com.xnx3.j2ee.shiro.ShiroFunc.getUserId;

@Controller
@RequestMapping("/QrCodeController")
public class QrCodeController {

    @Resource
    private SqlService sqlService;
    @Resource
    private QrCodeService qrCodeService;
    private String logUrl;

    String host = "http://www.cqpisa.cn:8030/";

    @RequestMapping("/qrCode.do")
    public String qrCode(Model model) {

        List<QrCode> qrCodeList = qrCodeService.queryQrCode(getUserId());
        if (!qrCodeList.isEmpty()) {

            String qrCodePath = "";
            String logopath = "";
            String backgroundColor = "";
            String frontViewColor = "";
            int id = 0;

            for (QrCode qrCode : qrCodeList) {
                qrCodePath = qrCode.getQrCodePath();
                logopath = qrCode.getLogoPath();
                backgroundColor = qrCode.getBackgroundColor();
                frontViewColor = qrCode.getFrontViewColor();
                id = qrCode.getId();
            }
            model.addAttribute("id", id);
            model.addAttribute("qrCodePath", qrCodePath);
            model.addAttribute("logopath", logopath);
            model.addAttribute("backgroundColor", backgroundColor);
            model.addAttribute("frontViewColor", frontViewColor);
        }
        return "site/qrCode";
    }

    @RequestMapping("/getQrCode.do")
    @ResponseBody
    public Map<String, Object> getQrCode(HttpServletRequest request, @RequestParam(value = "BLACK", required = false) int BLACK,
                                         @RequestParam(value = "WHITE", required = false) int WHITE) throws Exception {

        int backgroundcolor = 0xFFFFFFFF;
        int foregroundcolor = 0xFF000000;

        String forecolor = request.getParameter("BLACK");
        String backcolor = request.getParameter("WHITE");

        //将int格式的颜色值转换成16进制
//        Integer x = BLACK;
//        String backcolor = x.toHexString(x);
//        Integer y = WHITE;
//        String forecolor = y.toHexString(y);

        //判断获取的BLACK前景颜色是否为空
        if (BLACK > 0 && !"".equals(BLACK)) {
            foregroundcolor = BLACK;
        }

//        //判断获取的WHITE背景颜色是否为空
        if (WHITE > 0 && !"".equals(WHITE)) {
            backgroundcolor = WHITE;
        }
        String url = Url();
        Map<String, Object> map = new HashMap<>();
//        String url = "http://118.25.235.213:8030/rfpf/#/mains/" + getUserId();

        String userId = String.valueOf(getUserId());

//       String truePath = ClassLoader.getSystemResource("").getPath() + "site/" + getUserId() + "/LogoQrCode/";//本地使用
        String truePath = request.getServletContext().getRealPath("/") + "site/" + getUserId() + "/LogoQrCode/"; //服务器使用

        InetAddress address = InetAddress.getLocalHost();//获取的是本地的IP地址
        String hostAddress = address.getHostAddress();//192.168.0.121
//        String serverMappingPath = "/site/" + getUserId() + "/LogoQrCode/";//本地使用
        String serverMappingPath = "site/" + getUserId() + "/LogoQrCode/";//服务器使用

        String basePath = request.getServletContext().getRealPath("/");//服务器
//        String basePath = ClassLoader.getSystemResource("").getPath();//本地
        String logo = "";
        if (logUrl != null && logUrl != "") {
            logo = basePath + logUrl;
        }

        String qrPahth = QrcodeUtils.uploadAndCreateAndReuturnPath(userId, url, logo, serverMappingPath, truePath, hostAddress
                , request, null, foregroundcolor, backgroundcolor);
        logUrl = "";
        List<QrCode> qrCodeList = qrCodeService.queryQrCode(getUserId());
        if (!qrCodeList.isEmpty()) {
            map.put("qrCodeList", qrCodeList);
        }
        map.put("qrPaht", qrPahth);
        updateQrCode(backcolor, forecolor, logUrl, qrPahth, request);
        return map;
    }

    /***
     * 二维码生成成功后将数据保存在数据库中
     * **/

    public void updateQrCode(String backgroundcolor, String foregroundcolor, String logo, String qrPahth, HttpServletRequest request) {

        StringBuffer sbf = null;
        for (int i = 0; i <= 100; i++) {
            String sources = "0123456789"; // 加上一些字母，就可以生成pc站的验证码了
            Random rand = new Random();
            sbf = new StringBuffer();
            for (int j = 0; j < 6; j++) {
                sbf.append(sources.charAt(rand.nextInt(9)) + "");
            }

        }

        List<QrCode> qrCodeList = qrCodeService.queryQrCode(getUserId());
        QrCode qCode = new QrCode();
        if (!qrCodeList.isEmpty()) {

            int id = 0;
            for (QrCode qrCode : qrCodeList) {
                id = qrCode.getId();
            }
            QrCode qrCode = sqlService.findById(QrCode.class, id);
            qrCode.setUserId(getUserId());
            qrCode.setBackgroundColor(backgroundcolor);
            qrCode.setFrontViewColor(foregroundcolor);
            qrCode.setLogoPath(logo);
            qrCode.setQrCodePath(qrPahth + "?t=" + sbf);
            qrCodeService.updateQrCode(qrCode, getUserId(), request);
        } else {
            qCode.setUserId(getUserId());
            qCode.setBackgroundColor(backgroundcolor);
            qCode.setFrontViewColor(foregroundcolor);
            qCode.setLogoPath(logo);
            qCode.setQrCodePath(qrPahth + "?t=" + sbf);
            qrCodeService.updateQrCode(qCode, getUserId(), request);
        }
    }

    /**
     * 上传图片接口
     */
    @RequestMapping(value = "uploadLogoQrCode${url.suffix}", method = RequestMethod.POST)
    @ResponseBody
    public UploadFileVO uploadLogoQrCode(Model model, HttpServletRequest request) {

        UploadFileVO uploadFileVO = AttachmentFile.uploadImage("site/" + getUserId() + "/Logo/", request, "file", 0);
        if (uploadFileVO.getResult() == UploadFileVO.SUCCESS) {
            //上传成功，写日志
            logUrl = uploadFileVO.getPath();
            AliyunLog.addActionLog(getUserId(), "内容管理上传图片成功：" + uploadFileVO.getFileName(), uploadFileVO.getPath());
        }
        return uploadFileVO;
    }

    /***
     * 二维码下载
     * ***/
    @RequestMapping("/downloadPic.do")
    public void downloadPic(@RequestParam(value = "url", required = false) String url) {

        if (url != null && !"".equals(url)) {
            DownloadPicture.downloadPicture(url, "D:/download/" + getUserId() + ".jpg");
        }
    }

    @RequestMapping("/getUrl.do")
    @ResponseBody
    public String getUrl() {

        String url = Url();

        return url;
    }

    /********
     * 生成预览链接
     * *****/
    public String Url() {

        String webUrl = "";
        List<User> list = sqlService.findBySqlQuery("select * from user where id = "+ getUser().getId(),User.class);
        String code = list.get(0).getRoleCode();

        if (code.equals("ZMXC")) {
            webUrl = host + "zmxc/#/mains/" + getUserId();
        } else if (code.equals("ZJ")) {
            webUrl = host + "zj/#/mains/" + getUserId();
        } else if (code.equals("ZYDH")) {
            webUrl = host + "zydh/#/mains/" + getUserId();
        } else if (code.equals("JDYH")) {
            webUrl = host + "jdyh/#/mains/" + getUserId();
        } else if (code.equals("HZS")) {
            webUrl = host + "hzs/#/mains/" + getUserId();
        } else if (code.equals("GXS")) {
            webUrl = host + "gxs/#/mains/" + getUserId();
        } else if(code.equals("QY")){
            webUrl = host + "/rfpf/#/mains/" + getUserId();
        }else if(code.equals("JD")){
            webUrl = host + "/rfpf/#/mains/" + getUserId();
        }else{
            webUrl = "您没有权限耶！";
        }
        return webUrl;
    }


}
